<?php
  error_reporting(0);

  define('S_ARRAY',serialize(array()));

  define('DB_SERVER','********');
  define('DB_USER','************');
  define('DB_PASSWORD','*********');
  define('DB_TABLE','********');
  define('DB_CODING','SET NAMES "cp1251"');

  define('SESSION_TIME',42);
  define('SERVER_BUSY',42);

  if (($connection=mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD))&&mysql_select_db(DB_TABLE)&&  mysql_query(DB_CODING,$connection))
    define('DB_CONNECTED',1);


  function vk_db_validate($sess) {
    if (!defined('DB_CONNECTED')) return FALSE;
    if ((!$sess)||
        (!isset($sess[3]))||
        (strlen($sess[3])<4)||
        (!$uid = substr($sess[1],2))) return FALSE;
    return $uid;
  }


  function vk_db_insert($sess) {
    if (!$uid=vk_db_validate($sess)) return;
    return mysql_query('INSERT INTO `users` (uid,name,data,friends,msg) VALUES ('.$uid.',\'\',\''.S_ARRAY.'\',0,\'\')');
  }

  function vk_db_update($sess,$name,$value) {
    if (!$uid=vk_db_validate($sess)) return;
    switch ($name) {
    case 'name':
      return mysql_query('UPDATE `users` u SET u.'.$name.' = \''.strtr($value,array("\\"=>"\\\\","'"=>"\\'")).'\' WHERE u.uid = '.$uid);
      break;
    case 'friends':
      return mysql_query('UPDATE `users` u SET u.'.$name.' = '.$value.' WHERE u.uid = '.$uid);
      break;
    case 'msg':
      return mysql_query('UPDATE `users` u SET u.'.$name.' = \''.$value.'\' WHERE u.uid = '.$uid);
      break;
    default:
      return vk_db_data($sess,$name,$value);
      break;
    }
  }

  function vk_db_get_data($sess) {
    if (!$uid=vk_db_validate($sess)) return;
    if (!$q = mysql_query('SELECT u.data FROM `users` u WHERE u.uid = '.$uid.' LIMIT 0,1')) return;
    if (!$r = mysql_fetch_array($q,MYSQL_ASSOC)) return;
    return unserialize($r['data']);
  }

  function vk_db_set_data($sess,$data) {
    if (!$uid=vk_db_validate($sess)) return;
    return( mysql_query('UPDATE `users` u SET u.data = \''.strtr(serialize($data),array("\\"=>"\\\\","'"=>"\\'")).'\' WHERE u.uid = '.$uid));
  }

  function vk_db_data($sess,$name,$value) {
    if (!$uid=vk_db_validate($sess)) return;
    $data = vk_db_get_data($sess);
    if ($data === NULL) return;
    $data[$name]=$value;
    if (vk_db_set_data($sess,$data)) return TRUE;
  }

  function vk_db_getUsers($page=0,$sel='*') {
    if (!defined('DB_CONNECTED')) return FALSE;
    if (!$q = mysql_query('SELECT '.$sel.' FROM `users` u ORDER BY u.friends DESC LIMIT '.(($page>=0)?($page*10).',10':'0,'.(-$page)*10))) return;
    $t=array();
    while ($r=mysql_fetch_array($q,MYSQL_ASSOC)) {
      $r['data']=unserialize($r['data']);
      $t[]=$r;
    }
    return $t;  
  }

  function vk_db_usersCount() {
    if (!defined('DB_CONNECTED')) return FALSE;
    if (!$q = mysql_query('SELECT COUNT(*),SUM(u.friends) FROM `users` u')) return;
    $r = mysql_fetch_row($q);
    return $r;
  }
  
  function vk_db_create_sess() {
    if (!defined('DB_CONNECTED')) return;
    if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
      session_start();
    }

    if (isset($_SESSION['sessid'])&&!empty($_SESSION['sessid']))
    if (($q=mysql_query('SELECT COUNT(*) FROM `sess` s WHERE s.sessid = \''.htmlspecialchars($_SESSION['sessid']).'\''))
     &&($r=mysql_fetch_array($q))
     &&($r[0]>0))
      return $_SESSION['sessid'];
    
    $sessid=sha1('------------'.uniqid(time()).'-------------------');
    if (!$q = mysql_query('INSERT INTO `sess` VALUES (\''.$sessid.'\','.(time()+SESSION_TIME).')')) return;   

    return $sessid;
  }

  function vk_db_isBusy($location=TRUE) {
    if ($_SESSION)
    if (!empty($_SESSION['to'])&&($_SESSION['to']>time()))
    if($location) {
        header('Location: /full.html');
        if ($_SESSION) $_SESSION['to']=time()+60;
        exit();
    }
    if ((!defined('DB_CONNECTED'))||
        (!$q = mysql_query('SELECT COUNT(*) FROM `sess`'))||
        (!$r=(mysql_fetch_array($q)))
        ||($r[0]>SERVER_BUSY)) {
      if($location) {
        header('Location: /full.html');
        if ($_SESSION) $_SESSION['to']=time()+15;
        exit();
      }
      return TRUE;
    }
    return FALSE;
  }

  function vk_db_validate_sess() {
    if (!defined('DB_CONNECTED')) return FALSE;
    if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
      session_start();
    }
    $time = time();
    mysql_query('DELETE FROM `sess` WHERE `time` < '. $time);
    if (vk_db_isBusy(FALSE)) return FALSE;
    if (!isset($_SESSION['sessid'])||empty($_SESSION['sessid'])) return FALSE;
    $cursess=htmlspecialchars($_SESSION['sessid']);
    if (!$q = mysql_query('SELECT time FROM `sess` WHERE `sessid` = \''.$cursess.'\' AND `time` > '.time().' LIMIT 0,1')) return FALSE;

    if (!$r = mysql_fetch_array($q)) 
    return FALSE;

    mysql_query('UPDATE `sess` SET `time` = '.($time+SESSION_TIME).' WHERE `sessid` = \''.$cursess.'\'');
    return TRUE;
  }

  function vk_db_delete_sess() {
    if (!defined('DB_CONNECTED')) return FALSE;
    if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
      session_start();
    }
    if (!$q = mysql_query('DELETE FROM `sess` WHERE `sessid` = \''. htmlspecialchars($_SESSION['sessid']) .'\'')) return FALSE;
    return TRUE;
  }
?>